package com.changgou.file.util;

import com.changgou.file.pojo.FastDFSFile;
import org.csource.common.MyException;
import org.csource.common.NameValuePair;
import org.csource.fastdfs.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;

import java.io.*;

public class FastDFSUtil {


    private static Logger logger =  LoggerFactory.getLogger(FastDFSUtil.class);

    //加载配置文件
    /***
     * 初始化加载FastDFS的TrackerServer配置
     */
    static {
        try {
            String filePath = new ClassPathResource("fdfs_client.conf").getFile().getAbsolutePath();
            ClientGlobal.init(filePath);
        } catch (Exception e) {
            logger.error("FastDFS Client Init Fail!",e);
        }
    }

    /**
     * 获取storageClient
     * @return
     * @throws IOException
     */
    public static StorageClient getstorageClient() throws IOException {
        //创建一个Tracker访问客户端对象TrackerClient
        TrackerClient trackerClient = new TrackerClient();
        //通过tracker访问服务,获取链接信息
        TrackerServer trackerServer = trackerClient.getConnection();
        //通过链接信息获取Storage的链接信息,创建Storagelient并存储链接信息

        return new StorageClient(trackerServer,null);
    }


    //文件上传
    public static String[] upload(FastDFSFile fastDFSFile) throws IOException, MyException {
        NameValuePair[] nameValuePair = new NameValuePair[1];

        nameValuePair[0] = new NameValuePair("author",fastDFSFile.getAuthor());


        //通过StorageClient访问storage,实现文件上传,返回上传后的信息
        //字节数组  扩展名  附加信息


        StorageClient storageClient = null;
        String[] strings = new String[0];
        try {
           storageClient =  getstorageClient();
            /**
             * 返回的strings
             * strings[0] 所存储组的名字
             * strings[1] 文件存储到storage中的虚拟路径 M00/01/02/xxx.jpg
             */
            strings = storageClient.upload_file(fastDFSFile.getContent(), fastDFSFile.getExt(), nameValuePair);
        } catch (Exception e) {
            logger.error("Exception when uploadind the file:" + fastDFSFile.getName(), e);
        }
        if(strings == null && strings!=null){
            logger.error("upload file fail, error code:" + storageClient.getErrorCode());
        }
        return strings;
    }



    /**
     * 文件下载
     * @param groupName
     * @param fileName
     * @return
     * @throws IOException
     * @throws MyException
     */
    public static ByteArrayInputStream downloadFile(String groupName, String fileName) throws IOException, MyException {
        try {
            StorageClient storageClient = getstorageClient();

            byte[] bytes = storageClient.download_file(groupName, fileName);

            return new ByteArrayInputStream(bytes);
        } catch (Exception e) {
            logger.error("Exception: Get File from Fast DFS failed",e);
        }
        return null;
    }

    /***
     * 获取Storage组
     * @param groupName
     * @return
     * @throws IOException
     */
    public static StorageServer[] getStoreStorages(String groupName)
            throws IOException {
        //创建TrackerClient
        TrackerClient trackerClient = new TrackerClient();
        //获取TrackerServer
        TrackerServer trackerServer = trackerClient.getConnection();
        //获取Storage组
        return trackerClient.getStoreStorages(trackerServer, groupName);
    }





    /**
     *获取文件信息
     * @param groupName 组名
     * @param fileName  文件名
     * @return
     * @throws Exception
     */
    public static FileInfo getFile(String groupName, String fileName) throws Exception {

        try {
            return getstorageClient().get_file_info(groupName,fileName);
        } catch (Exception e) {
            logger.error("Exception: Get File from Fast DFS failed",e);
        }
        return null;

    }

    /**
     * 删除文件
     * @param groupName
     * @param fileName
     * @throws IOException
     * @throws MyException
     */
    public static void deleteFile(String groupName, String fileName) throws IOException, MyException {

        getstorageClient().delete_file(groupName, fileName);

    }

    /***
     * 获取Storage信息,IP和端口
     * @param groupName
     * @param remoteFileName
     * @return
     * @throws IOException
     */
    public static ServerInfo[] getFetchStorages(String groupName,
                                                String remoteFileName) throws IOException {
        TrackerClient trackerClient = new TrackerClient();
        TrackerServer trackerServer = trackerClient.getConnection();
        return trackerClient.getFetchStorages(trackerServer, groupName, remoteFileName);
    }

    /***
     * 获取Tracker服务地址
     * @return
     * @throws IOException
     */
    public static String getTrackerUrl() throws IOException {

        TrackerClient trackerClient = new TrackerClient();
        TrackerServer trackerServer = trackerClient.getConnection();
        return "http://"+trackerServer.getInetSocketAddress().getHostString()+":"+ClientGlobal.getG_tracker_http_port()+"/";
    }


    public static void main(String[] args) throws Exception {
        /*FileInfo file = getFile("group1", "M00/00/00/wKjAwF7PNlGAW2clAAHN_V9N2s0391.jpg");
        System.out.println(file.getSourceIpAddr());
        System.out.println(file.getCreateTimestamp());*/

        ByteArrayInputStream is = downloadFile("group1", "M00/00/00/wKjAwF7PclyAWzqWAAa_Drx47TM035.jpg");

        //将文件写入到本地磁盘
        FileOutputStream fileOutputStream = new FileOutputStream("D:/fastdfs");

        //定义一个缓冲区
        byte[]  buffer = new byte[1024];
        while(is.read()!=-1){
            fileOutputStream.write(buffer);
        }
        fileOutputStream.flush();
        fileOutputStream.close();
        is.close();

       //deleteFile("group1","M00/00/00/wKjAwF7PNlGAW2clAAHN_V9N2s0391.jpg");


    }

}
